﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;

namespace DotNETX.Version.Manager
{
    public class TextBoxFix
    {
        public static bool GetUpdateSourceOnTextChanged(DependencyObject obj)
        {
            return (bool)obj.GetValue(UpdateSourceOnTextChangedProperty);
        }

        public static void SetUpdateSourceOnTextChanged(DependencyObject obj, bool value)
        {
            obj.SetValue(UpdateSourceOnTextChangedProperty, value);
        }

        public static DependencyProperty UpdateSourceOnTextChangedProperty = DependencyProperty.RegisterAttached("UpdateSourceOnTextChanged", typeof(bool), typeof(TextBoxFix), new PropertyMetadata(false, OnUpdateSourceOnTextChangedChanged));
        private static void OnUpdateSourceOnTextChangedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (!(d is TextBox)) return;
            TextBox txt = d as TextBox;
            if ((bool)e.NewValue)
            {
                try
                {
                    txt.TextChanged += OnTextChanged;
                }
                catch { }
            }
            else
            {
                try
                {
                    txt.TextChanged -= OnTextChanged;
                }
                catch { }
            }
        }
        private static void OnTextChanged(object sender, TextChangedEventArgs e)
        {
            TextBox txt = sender as TextBox;
            txt.GetBindingExpression(TextBox.TextProperty).UpdateSource();
        }
    }
}
